package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;

import cn.hd01.repository.MonthlyTargetRepository;
import cn.hd01.repository.entity.MonthlyTarget;
import cn.hd01.service.MonthlyTargetService;

@Service
public class MonthlyTargetServiceImpl extends BaseServiceImpl<MonthlyTarget, Integer> implements MonthlyTargetService {

	private MonthlyTargetRepository repository;
	
	@Autowired
	public MonthlyTargetServiceImpl(MonthlyTargetRepository repository) {
		super(repository);
		this.repository = repository;
	}
	
	@Override
	public Page<MonthlyTarget> findAll(final MonthlyTarget monthlyTarget, Pageable pageable) {
		if (monthlyTarget == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<MonthlyTarget>() {
			@Override
			public Predicate toPredicate(Root<MonthlyTarget> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
		
	}

	@Override
	public int updateMonthlyTarget(Double amount, Date targetTime, Integer id) {
		return repository.updateMonthlyTarget(amount, targetTime, id);
	}
	
}
